/**
 * Description:
 * Class Name:HashSetTest2
 * Date:2022/2/26 14:50
 *
 * @author LTisme
 * @version JAVA17
 */
package 疯狂Java讲义.第8章_Java集合._8_3_Set集合._8_3_1_HashSet类;

import java.util.HashSet;

class R{
    int count;
    public R(int count){
        this.count = count;
    }

    @Override
    public String toString() {
        return "R{" +
                "count=" + count +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        R r = (R) o;
        return count == r.count;
    }

    @Override
    public int hashCode() {
        return this.count;
    }
}

public class HashSetTest2 {
    public static void main(String[] args) {
        var temp = new R(-2);

        var hs = new HashSet();
        hs.add(new R(5));
        hs.add(new R(-3));
        hs.add(new R(9));
//        hs.add(new R(-2));
        hs.add(temp);
        // 打印HashSet集合，集合元素没有重复
        System.out.println(hs);
        // 取出第一个元素
        var it = hs.iterator();
        R first = (R)it.next();

        // 为第一个元素的count实例变量赋值
        first.count = -3;                                     // ①
        // 再次输出HashSet集合，集合元素有重复元素
        System.out.println("----------------");
        System.out.println(hs);

        // 删除count为-3的R对象
        hs.remove(new R(-3));
        // 可以看到被删除了一个R元素
        System.out.println("----------------");
        System.out.println(hs);
        System.out.println("hs是否包含count为-3的R对象？" +
                hs.contains(new R(-3)));                // 输出false
        System.out.println("hs是否包含count为-2的R对象？" +
                hs.contains(new R(-2)));                // 输出false

        System.out.println(temp.equals(new R(-3)));
    }
}
//[R{count=-2}, R{count=-3}, R{count=5}, R{count=9}]
//----------------
//[R{count=-3}, R{count=-3}, R{count=5}, R{count=9}]
//----------------
//[R{count=-3}, R{count=5}, R{count=9}]
//hs是否包含count为-3的R对象？false
//hs是否包含count为-2的R对象？false
